using System;
using ServiceStack.ServiceHost;
using ODSearchEngine;
using log4net;
using ODSWebService.DTO.Requests;
using ODSWebService.DTO.Responses;

namespace ODSWebService
{
	public class IndexService : IService<IndexRequest>
	{
		private static readonly ILog logger = LogManager.GetLogger(typeof(IndexService));
		private IIndexEngine indexEngine = null;
		
		public IndexService ()
		{
			this.indexEngine = IocManager.Get<IIndexEngine>();
			if(logger.IsDebugEnabled)
				logger.DebugFormat("Got index engine {0}.", this.indexEngine);
		}

		#region IService[IndexRequest] implementation
		public object Execute (IndexRequest request)
		{
			request.Data.Add("ID", Guid.NewGuid().ToString());
			if(logger.IsDebugEnabled)
				logger.DebugFormat("Executing indexation for {0}.", request.Data);
			IndexResponse result = new IndexResponse();
			try
			{				
				if(request.Data.Keys.Count > 0)
				{
					this.indexEngine.IndexData(request.Data);
					result.Result = IndexResponse.IndexResult.Success;
				}
				else
				{
					result.Result = IndexResponse.IndexResult.Failure;
				}
			}
			catch
			{
				result.Result = IndexResponse.IndexResult.Failure;
			}
			if(logger.IsDebugEnabled)
				logger.DebugFormat("Indexation completed. Result: {0}", result);
			return result;
		}
		#endregion
}
}

